/**
 * 字典项列表。每次只显示一个字典类型下的字典项，可编辑。
 * @author linzongxue
 * @create_date 2012-2-15
 */
define(function(){
	var DictRecord = Ext.data.Record.create(['id', 'text', 'value', 'memo']);
	var ItemGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
		dictType: null, //当前选中的字典类型
		height: au.getMainPanel().getHeight()/2.5,
		stripeRows: true,
	    enableHdMenu: false,
	    clicksToEdit: 1,
        split: true,
        autoScroll: true,
	    autoExpandColumn: 2,
	    initComponent: function(){
	    	ItemGridPanel.superclass.initComponent.call(Ext.apply(this, {
	    		tbar: au.permit([
	    		    {xtype:'label', text:'字典项列表', style:'font-weight:bold;margin-right:5px;'},
					{xtype: 'label', name:'curType', text:'未选中字典类型'},
					'->',
	            	{text: '添加', permitId:'sys.dict.updateItem', handler: function(){this.addRow();},scope: this, iconCls: 'icon-add', tooltip:'添加字典项'},
	            	{text: '保存', permitId:'sys.dict.updateItem', handler: this.save, scope: this, iconCls: 'icon-save', tooltip:'保存对字典项的更改'},
					'-',
					{text: '刷新', handler: function(){this.refresh(this.dictType);}, scope: this, iconCls: 'icon-refresh'},
					'-'
	            ]),
			    sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
	            store: new Ext.data.JsonStore({recordType: DictRecord}),
	            columns:[
 				    {header: '字典值', width: 100, dataIndex: 'value', editor: {xtype: 'numberfield', allowBlank: false}},
 					{header: '显示值', width: 180, dataIndex: 'text', editor: {allowBlank: false}},
 					{header: '说明', width: 180, dataIndex: 'memo', editor: {}},
 					{
 						xtype: 'actioncolumn',width: 30, items: [{
 		                    icon: cu.getIconImg('cancel.gif'),
 		                    tooltip: '<nobr>删除此行</nobr>',
 		                    handler: function(grid, rowIndex, colIndex) {
 		                        grid.getStore().removeAt(rowIndex);
 		                    }
 		                }]
 					}
 				]
			}));
	    },
	    addRow: function(data){
	    	var count = this.store.getCount();
	    	data = data || {value: count + 1}; //新字典项的值自动加1
	    	this.store.add(new DictRecord(data));
            this.startEditing(count, 1);
	    },
	    /**
	     * 指定字典类型刷新数据
	     */
	    refresh: function(dictType){
	    	this.dictType = dictType;
	    	var typeLabel = this.getTopToolbar().find('name', 'curType')[0];
	    	this.store.removeAll();
	    	if (dictType){
	    		typeLabel.setText('当前类型：' + dictType.name + ' (' + dictType.text + ')');
	    		cu.get({
	    			url: 'sys/dict/getItemsByTypeId.do',
	    			params: {typeId: dictType.id},
	    			success: function(data){
	    				Ext.each(data, function(item){
	    					this.addRow(item);
	    				}, this);
	    			},
	    			waitMsg: null,
	    			scope: this
	    		});
	    	}
	    	else{
	    		typeLabel.setText('未选中字典类型');
	    	}
	    },
	    /**
	     * 保存对字典项的修改
	     */
	    save: function(){
	    	if (!this.dictType){
	    		cu.hint('没有选择字典类型');
	    		return;
	    	}
	    	//从字典项列表中组合参数
	    	var params = this.generateItemParams();
	    	if (!params) return;
	    	//提交请求
	    	cu.post({
	    		url: 'sys/dict/saveDictItems.do',
	    		params: params,
	    		success: function(){
	    			cu.hint('保存成功');
	    		}
	    	});
	    },
	    /**
	     * 从字典项列表中组合参数，同时做校验。
	     * 校验不通过返回null，通过则返回组合后的请求参数。
	     */
	    generateItemParams: function(){
	    	var params = {typeId: this.dictType.id};
	    	for (var row = 0; row < this.store.getCount(); row ++){
				var record = this.store.getAt(row);
				if (lu.int(record.get('value'), 0) <= 0){
					cu.alert('第{0}个字典项不正确：字典值必须是大于0的整数'.f(row + 1), function(){
						this.startEditing(row, 0);
					}, this);
					return null;
				}
				if (lu.isEmpty(record.get('text'))){
					cu.alert('第{0}个字典项不正确：显示值不能为空'.f(row + 1), function(){
						this.startEditing(row, 1);
					}, this);
					return null;
				}
				//检查重复
				for (var j = row + 1; j < this.store.getCount(); j ++){
					if (record.get('value') == this.store.getAt(j).get('value')){
						cu.alert('第{0}个字典项的值有重复：{1}'.f(j + 1, record.get('value')), function(){
							this.startEditing(j, 0);
						}, this);
						return null;
					}
				}
				//组合参数
				this.store.fields.eachKey(function(fieldName){
					params['items[{0}].{1}'.f(row,fieldName)] = record.get(fieldName);
				});
				record.commit();
			}
			return params;
	    }
	});
	return ItemGridPanel;
});